import django.http as http
import django.shortcuts as shortcuts
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import ContentType
import django.utils

from django_metatagging.utils import tagged_objects
import django_utils.pagination as pagination
import django_utils.request_helpers as request_helpers

def objects_with_tag(request, content_type, tag, related_tags = False):
    page = request_helpers.get_page(request)
    sort = request_helpers.get_sort(request,  'most_popular')
    
    objects, related_tags_list = tagged_objects(content_type, tag, related_tags)
    current_page,  page_range = pagination.paginate_queryset(objects,  10,  5,  page)
    safe_tag = django.utils.http.urlquote(tag)
    
    return shortcuts.render_to_response('django_metatagging/objects_with_tag.html',
                                        {'current_page':current_page,  'page_range':page_range, 'tag':tag},
                                        context_instance = RequestContext(request))
    
def browse(request):
    page = request_helpers.get_page(request)
    tags = models.MetaTag.objects.all().order_by('name')
    form = forms.TagSearchForm()
    
    paginator = pagination.DiggPaginator(tags, 10, body=5)
    current_page = paginator.page(page)
    page_range = paginator.page_range
    object_count = len(current_page.object_list)
    
    for tag in current_page.object_list:
        tag.count = models.Tag.objects.filter(tag = tag).count()
        tag.safe_name = django.utils.http.urlquote(tag.name)
        
    return shortcuts.render_to_response(
        'taxanomy/browse.html', 
        {'current_page':current_page,  'page_range':page_range,   'form':form}, 
        context_instance = RequestContext(request), 
    )

def browse_ajax(request,  tag):
    import re
    
    page = request_helpers.get_page(request)
    escaped_tag = re.escape(tag.strip()[1:-1])
    pattern = "^%s.*" % (escaped_tag)
    tags = models.MetaTag.objects.filter(name__iregex = pattern).order_by('name')
    form = forms.TagSearchForm()
    
    paginator = pagination.DiggPaginator(tags, 10, body=5)
    current_page = paginator.page(page)
    page_range = paginator.page_range
    object_count = len(current_page.object_list)
    
    for tag in current_page.object_list:
        tag.count = models.Tag.objects.filter(tag = tag).count()
        tag.safe_name = django.utils.http.urlquote(tag.name)
        
    return shortcuts.render_to_response(
        'taxanomy/browse_ajax.html', 
        {'current_page':current_page,  'page_range':page_range,   'form':form}, 
        context_instance = RequestContext(request), 
    )